<template>
  <div class="comment-section">
    <!-- 评论统计和操作栏 -->
    <div class="comment-header">
      <div class="comment-title-section">
        <h3 class="comment-title">
          <i class="el-icon-chat-dot-round"></i>
          商品评论 ({{ total }})
        </h3>
        <div class="comment-stats">
          <div class="rating-overview">
            <span class="avg-rating">{{ averageRating.toFixed(1) }}</span>
            <el-rate
              v-model="averageRating"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            ></el-rate>
          </div>
        </div>
      </div>
      <!-- 发表评论按钮 -->
      <div class="comment-actions" v-if="currentUserId">
        <el-button 
          type="primary" 
          icon="el-icon-edit"
          @click="showCommentDialog"
          class="add-comment-btn"
        >
          发表评论
        </el-button>
      </div>
    </div>
    <!-- 评论列表 -->
    <div class="comment-list">
      <el-card v-if="comments.length === 0" class="empty-comment">
        <div class="empty-content">
          <i class="el-icon-chat-line-round"></i>
          <p>暂无评论，快来发表第一条评论吧！</p>
          <el-button 
            v-if="currentUserId"
            type="primary" 
            @click="showCommentDialog"
            class="first-comment-btn"
          >
            发表第一条评论
          </el-button>
        </div>
      </el-card>
      <div v-else class="comments-container">
        <CommentItem
          v-for="comment in comments"
          :key="comment.id"
          :comment="comment"
          :current-user-id="currentUserId"
          :goods-id="goodsId"
          :is-reply="false"
          @comment-deleted="handleCommentDeleted"
          @reply-added="handleReplyAdded"
        />
      </div>
    </div>
    <!-- 分页 -->
    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total"
        background
      ></el-pagination>
    </div>
    <!-- 评论弹窗 -->
    <CommentDialog
      :visible.sync="dialogVisible"
      :goods-id="goodsId"
      :current-user-id="currentUserId"
      @comment-added="handleCommentAdded"
    />
  </div>
</template>

<script>
import CommentItem from "./CommentItem.vue";
import CommentDialog from "./CommentDialog.vue";

export default {
  name: "CommentSection",
  components: {
    CommentItem,
    CommentDialog
  },
  props: {
    goodsId: {
      type: [String, Number],
      required: true
    },
    currentUserId: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      comments: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      dialogVisible: false
    };
  },
  computed: {
    averageRating() {
      if (this.comments.length === 0) return 0;
      // 只计算主评论（parentId=0）的评分
      const mainComments = this.comments.filter(comment => comment.parentId === 0);
      if (mainComments.length === 0) return 0;
      const totalRating = mainComments.reduce((sum, comment) => sum + comment.rating, 0);
      return totalRating / mainComments.length;
    }
  },
  mounted() {
    this.fetchComments();
  },
  watch: {
    goodsId() {
      this.currentPage = 1;
      this.fetchComments();
    }
  },
  methods: {
    // 获取评论列表
    fetchComments() {
      if (!this.goodsId) return;
      
      this.loading = true;
      this.$axios
        .get(`/comment/goods/${this.goodsId}`, {
          params: {
            current: this.currentPage,
            size: this.pageSize
          }
        })
        .then(resp => {
          if (resp && resp.status === 200 && resp.data.success) {
            const data = resp.data.data;
            // 直接平铺所有评论
            this.comments = data.records.map(item => ({
              ...item,
              showReply: false,
              replyContent: '',
              replying: false
            }));
            this.total = data.total;
            this.checkLikeStatus();
          }
        })
        .catch(error => {
          console.error("获取评论失败:", error);
          this.$message.error("获取评论失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 检查评论点赞状态
    checkLikeStatus() {
      if (!this.currentUserId) return;
      
      this.comments.forEach(comment => {
        // 由于没有提供检查评论点赞状态的接口，这里暂时设置为false
        // 如果需要检查点赞状态，需要后端提供相应的接口
        comment.isLiked = false;
      });
    },

    // 显示评论弹窗
    showCommentDialog() {
      if (!this.currentUserId) {
        this.$message.warning("请先登录");
        return;
      }
      this.dialogVisible = true;
    },

    // 评论添加成功后的回调
    handleCommentAdded() {
      this.fetchComments();
      this.$emit("comment-added");
    },

    // 评论删除成功后的回调
    handleCommentDeleted(commentId) {
      this.comments = this.comments.filter(comment => comment.id !== commentId);
      this.total = Math.max(0, this.total - 1);
      this.$emit("comment-deleted");
    },

    // 回复添加成功后的回调
    handleReplyAdded() {
      this.fetchComments();
    },

    // 分页处理
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchComments();
    }
  }
};
</script>

<style scoped>
.comment-section {
  padding: 30px;
  width: 100%;
  box-sizing: border-box;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.comment-title-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.comment-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
  display: flex;
  align-items: center;
}

.comment-title i {
  margin-right: 10px;
  color: #00caa8;
}

.comment-stats {
  display: flex;
  align-items: center;
}

.rating-overview {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avg-rating {
  font-size: 24px;
  font-weight: 600;
  color: #ff9900;
}

.comment-actions {
  display: flex;
  gap: 12px;
}

.add-comment-btn {
  background: #00caa8;
  border: none;
  padding: 12px 24px;
  border-radius: 10px;
  font-weight: 500;
  transition: all 0.3s ease;
  font-size: 14px;
}

.add-comment-btn:hover {
  background: #00b894;
  transform: translateY(-1px);
}

/* 评论列表 */
.comment-list {
  margin-top: 20px;
}

.empty-comment {
  text-align: center;
  padding: 40px;
  border-radius: 10px;
}

.empty-content {
  color: #999;
}

.empty-content i {
  font-size: 48px;
  margin-bottom: 12px;
  color: #ddd;
}

.empty-content p {
  margin: 15px 0;
  font-size: 16px;
}

.first-comment-btn {
  margin-top: 15px;
  background: #00caa8;
  border: none;
  padding: 12px 24px;
  border-radius: 10px;
  font-weight: 500;
}

.first-comment-btn:hover {
  background: #00b894;
}

.comments-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 分页 */
.pagination-container {
  margin-top: 30px;
  text-align: center;
}

/deep/ .el-pagination .el-pager li.is-active {
  background-color: #00caa8;
  color: white;
  border-radius: 8px;
}

/deep/ .el-button--primary {
  background-color: #00caa8;
  border-color: #00caa8;
  border-radius: 10px;
}

/deep/ .el-button--primary:hover {
  background-color: #00b894;
  border-color: #00b894;
}
</style>
